package clientSide;

import java.util.HashMap;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import common.Message;
import common.MessageType;

public class ChatForm extends Shell {
	private CTabFolder tabFolder;
	private Client client;
	private HashMap<String, Integer> instanceIndex;
	boolean show = true;

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */

	public void Show() {
		open();
		layout();
		while (!isDisposed() && show) {
			if (!Display.getCurrent().readAndDispatch())
				Display.getCurrent().sleep();
			else {
				if (client.HasMessage()) {
					try {
						Message msg = client.getMessage(false);
						if (msg.getType() == MessageType.SendMessage) {
							client.RemoveMessage();
							AddMessage(msg);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * Create the shell.
	 * 
	 * @param display
	 */
	public ChatForm(Display display, Client client) {
		super(display, SWT.SHELL_TRIM | SWT.BORDER);
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.keyCode == 27)// esc key
					close();
			}
		});
		addListener(SWT.Close, new Listener() {
			@Override
			public void handleEvent(Event event) {
				// TODO Auto-generated method stub
				event.doit = true;
				show = false;
			}
		});
		setLayout(new GridLayout(1, false));
		instanceIndex = new HashMap<>();
		this.client = client;
		tabFolder = new CTabFolder(this, SWT.BORDER);
		tabFolder.setTabPosition(SWT.BOTTOM);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
		tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));
		createContents();
	}

	/**
	 * Create contents of the shell.
	 */
	protected void createContents() {
		setText("");
		setSize(450, 470);
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public synchronized void AddClient(String target) {
		if (instanceIndex.containsKey(target))
			return;
		InstanceChat instancechat = new InstanceChat(tabFolder, SWT.NONE,
				target, client);
		CTabItem item = new CTabItem(tabFolder, SWT.NONE);
		ImageData imgdata = new ImageData("src/Image/icon_close.gif");
		item.setImage(new Image(tabFolder.getDisplay(), imgdata));
		tabFolder.addMouseListener(new MouseListener() {
			@Override
			public void mouseUp(MouseEvent arg0) {
				CTabFolder curFolder = (CTabFolder) arg0.widget;
				Point eventLocation = new Point(arg0.x, arg0.y);
				CTabItem item = curFolder.getItem(eventLocation);
				if (item == null)
					return;
				Image image = item.getImage();

				// check if click is on image
				if (eventLocation.x >= item.getBounds().x + image.getBounds().x
						&& eventLocation.x <= item.getBounds().x
								+ image.getBounds().x + image.getBounds().width
						&& eventLocation.y >= item.getBounds().y
								+ image.getBounds().y
						&& eventLocation.y <= item.getBounds().y
								+ image.getBounds().y
								+ image.getBounds().height) {
					if (tabFolder.getItemCount() == 1)
						return;
					System.out.println("Close tab");
					String current = getText();
					instanceIndex.remove(item.getText().trim());
					String[] content = current.split(",");
					current = "";
					for (String s : content)
						if (!s.trim().equalsIgnoreCase(item.getText())
								&& s.trim().length() > 1)
							current += "," + s;
					current = current.substring(1);
					setText(current);
					item.dispose();
				} else {
					System.out.println("Don't close tab");
				}
			}

			@Override
			public void mouseDown(MouseEvent arg0) {
			}

			@Override
			public void mouseDoubleClick(MouseEvent arg0) {
			}
		});
		item.setControl(instancechat);
		item.setText(target);
		instanceIndex.put(target.trim(), tabFolder.getItemCount() - 1);
		String current = getText();
		if (current.length() < 1)
			current += target;
		else
			current += ", " + target;
		setText(current);
		setMinimized(false);
	}

	public void AddMessage(final Message msg) {
		String rec = msg.getSender().trim();
		int index = (int) instanceIndex.get(rec);
		Control c = (InstanceChat) tabFolder.getItem(index).getControl();
		InstanceChat instance = (InstanceChat) c;
		instance.AddMessage(msg);
	}
}
